// 通用JavaScript工具函数

// 获取URL参数
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 获取状态样式类
function getStatusClass(status) {
    const statusMap = {
        'PENDING_AUDIT': 'pending',
        'PROCESSING': 'processing',
        'COMPLETED': 'completed',
        'REJECTED': 'rejected'
    };
    return statusMap[status] || 'pending';
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'PENDING_AUDIT': '待审核',
        'PROCESSING': '处理中',
        'COMPLETED': '已完成',
        'REJECTED': '已拒绝'
    };
    return statusMap[status] || status;
}

// 获取类型文本
function getTypeText(type) {
    const typeMap = {
        'RETURN': '退货',
        'EXCHANGE': '换货',
        'REPAIR': '维修'
    };
    return typeMap[type] || type;
}

// 显示消息
function showMessage(message, type = 'info') {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.textContent = message;
    
    // 插入到页面顶部
    document.body.insertBefore(messageDiv, document.body.firstChild);
    
    // 3秒后自动移除
    setTimeout(() => {
        messageDiv.remove();
    }, 3000);
}

// 显示加载状态
function showLoading(container) {
    container.innerHTML = `
        <div class="loading">
            <div class="spinner"></div>
            <p>加载中...</p>
        </div>
    `;
}

// 隐藏加载状态
function hideLoading(container) {
    const loadingElement = container.querySelector('.loading');
    if (loadingElement) {
        loadingElement.remove();
    }
}

// 显示错误信息
function showError(container, message) {
    container.innerHTML = `
        <div class="message message-error">
            ${message}
        </div>
    `;
}

// 显示空状态
function showEmptyState(container, message = '暂无数据') {
    container.innerHTML = `
        <div style="text-align: center; padding: 40px; color: #666;">
            <p>${message}</p>
        </div>
    `;
}

// API请求封装
async function apiRequest(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.message || '请求失败');
        }
        
        return data;
    } catch (error) {
        console.error('API请求失败:', error);
        throw error;
    }
}

// 表单验证
function validateForm(formData) {
    const errors = [];
    
    for (let [key, value] of formData.entries()) {
        if (!value || value.trim() === '') {
            errors.push(`${key} 不能为空`);
        }
    }
    
    return errors;
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// 本地存储工具
const storage = {
    set(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            console.error('存储数据失败:', error);
        }
    },
    
    get(key, defaultValue = null) {
        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(item) : defaultValue;
        } catch (error) {
            console.error('读取数据失败:', error);
            return defaultValue;
        }
    },
    
    remove(key) {
        try {
            localStorage.removeItem(key);
        } catch (error) {
            console.error('删除数据失败:', error);
        }
    },
    
    clear() {
        try {
            localStorage.clear();
        } catch (error) {
            console.error('清空数据失败:', error);
        }
    }
};

// 导出到全局
window.utils = {
    getUrlParameter,
    formatDate,
    getStatusClass,
    getStatusText,
    getTypeText,
    showMessage,
    showLoading,
    hideLoading,
    showError,
    showEmptyState,
    apiRequest,
    validateForm,
    debounce,
    throttle,
    storage
}; 